package com.yipinhouse.signing.app.appImpl;

import cn.hutool.core.bean.BeanUtil;
import com.yipinhouse.common.result.Result;
import com.yipinhouse.signing.client.ContractManageClient;
import com.yipinhouse.signing.client.param.UploadContractAttachmentParam;
import com.yipinhouse.signing.client.param.UploadContractParam;
import com.yipinhouse.signing.service.ContractAttachmentService;
import com.yipinhouse.signing.service.ContractService;
import com.yipinhouse.signing.service.param.ContractAttachmentModel;
import com.yipinhouse.signing.service.param.UploadContractServiceParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/contract")
public class ContractManageApiImpl implements ContractManageClient {

    @Resource
    private ContractService service;

    @Resource
    private ContractAttachmentService contractAttachmentService;


    @Override
    public Result uploadContract(UploadContractParam param){
        log.info("上传合同详情，参数：{}",param);
        UploadContractServiceParam tempParam = BeanUtil.toBean(param, UploadContractServiceParam.class);
        service.uploadContract(tempParam);
        return Result.getInstance().setMsg("上传合同详情成功！");
    }

    @Override
    public Result uploadContractAttachment(UploadContractAttachmentParam param) throws Exception {
        log.info("上传合同图片：参数：{}",param);

//        获取文件输入对象
        MultipartFile[] files = param.getFiles();
        List<ContractAttachmentModel> fileList = new ArrayList<>();
        for (MultipartFile file : files) {
            ContractAttachmentModel model = new ContractAttachmentModel();
            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            String newName = System.currentTimeMillis()+suffix;
            model.setFileName(newName);
            model.setFileSuffix(suffix);
            model.setSize(file.getSize());
            model.setOldFileName(file.getOriginalFilename());
            model.setInputStream(file.getInputStream());
            fileList.add(model);
        }
        contractAttachmentService.uploadContractAttachment(fileList,param.getContractId());

        return Result.getInstance().setMsg("上传合同图片成功！");
    }
}
